/**
 * Copyright &copy; 2013-2015 山东易科德软件有限公司 All rights reserved.
 */
package cn.net.ecode.modules.sys.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.net.ecode.common.config.Global;
import cn.net.ecode.common.persistence.Page;
import cn.net.ecode.common.utils.StringUtils;
import cn.net.ecode.common.web.BaseController;
import cn.net.ecode.modules.sys.entity.Menu;
import cn.net.ecode.modules.sys.entity.Role;
import cn.net.ecode.modules.sys.service.MenuService;
import cn.net.ecode.modules.sys.service.RoleService;
import cn.net.ecode.modules.sys.utils.UserUtils;

/**
 * 角色Controller
 * 
 * @author ThinkGem
 * @version 2014-8-19
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/role")
public class RoleController extends BaseController {

	@Autowired
	private RoleService roleService;
	@Autowired
	private MenuService menuService;

	@ModelAttribute
	public Role get(String roleCode, boolean isNewRecord) {
		return roleService.get(roleCode, isNewRecord);
	}

	@RequiresPermissions("sys:role:view")
	@RequestMapping(value = {"list", ""})
	public String list(Role role, Model model) {
		return "modules/sys/roleList";
	}

	@RequiresPermissions("sys:role:view")
	@ResponseBody
	@RequestMapping(value = "listData")
	public Page<Role> listData(Role role, HttpServletRequest request, HttpServletResponse response) {
		// 如果不是超级管理员，则值显示非系统角色
		if (!role.getCurrentUser().isSuperAdmin()){
			role.setIsSys(Global.NO);
		}
		Page<Role> page = roleService.findPage(new Page<Role>(request, response), role);
		return page;
	}

	@RequiresPermissions("sys:role:view")
	@RequestMapping(value = "form")
	public String form(Role role, Model model,HttpServletRequest request) {
		// 如果是管理员，显示全部菜单
		if (UserUtils.getUser().isAdmin()){
			model.addAttribute("menuList", menuService.findList(new Menu()));
		}
		// 其它用户，显示当前有权限的菜单
		else{
			model.addAttribute("menuList", UserUtils.getMenuList());
		}
		model.addAttribute("type", request.getParameter("type"));
		model.addAttribute("role", role);
		return "modules/sys/roleForm";
	}

	@RequiresPermissions("sys:role:edit")
	@ResponseBody
	@RequestMapping(value = "save")
	public String save(Role role, Model model,HttpServletRequest request) {
		if (Global.isDemoMode()) {
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		if (StringUtils.isBlank(role.getIsSys())){
			role.setIsSys(Global.NO); // 非系统内置
		}
		if (StringUtils.isBlank(role.getIsShow())){
			role.setIsShow(Global.YES);// 显示
		}
//		if (!Global.YES.equals(role.getIsShow())){
//			return renderResult(Global.FALSE, "非法操作，不能够操作此角色！");
//		}
		if (Global.YES.equals(role.getIsSys()) && !role.getCurrentUser().isSuperAdmin()){
			return renderResult(Global.FALSE, "越权操作，只有超级管理员才能修改此数据！");
		}
		StringBuilder builder = new StringBuilder();
		if (!beanValidator(builder, role)) {
			return renderResult(Global.FALSE, builder.toString());
		}
		if (!"true".equals(checkName(role.getOldName(), role.getRoleName()))) {
			return renderResult(Global.FALSE, "保存角色'" + role.getRoleName() + "'失败, 角色名已存在");
		}
//		if (!"true".equals(checkEnname(role.getOldEnname(), role.getNameEn()))) {
//			return renderResult(Global.FALSE, "保存角色'" + role.getRoleName() + "'失败, 英文名已存在");
//		}
		roleService.save(role, request.getParameter("type"));
		return renderResult(Global.TRUE, "保存角色'" + role.getRoleName() + "'成功！");
	}
	
	/**
	 * 更新显示角色
	 * @param role
	 * @return
	 */
	@RequiresPermissions("sys:role:edit")
	@ResponseBody
	@RequestMapping(value = "show")
	public String show(Role role){
		if (Global.isDemoMode()) {
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		roleService.show(role);
		return renderResult(Global.TRUE, "显示角色成功！");
	}
	
	/**
	 * 更新隐藏角色
	 * @param role
	 * @return
	 */
	@RequiresPermissions("sys:role:edit")
	@ResponseBody
	@RequestMapping(value = "hide")
	public String hide(Role role){
		if (Global.isDemoMode()) {
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		roleService.hide(role);
		return renderResult(Global.TRUE, "隐藏角色成功！");
	}
	
	@RequiresPermissions("sys:role:edit")
	@ResponseBody
	@RequestMapping(value = "delete")
	public String delete(Role role) {
		if (Global.isDemoMode()) {
			return renderResult(Global.FALSE, "演示模式，不允许操作！");
		}
		if (Role.SUPER_ADMIN_ROLE_CODE.equals(role.getRoleCode())
				|| Role.SEC_ADMIN_ROLE_CODE.equals(role.getRoleCode())
				|| Role.CORP_ADMIN_ROLE_CODE.equals(role.getRoleCode())){
			return renderResult(Global.FALSE, "非法操作，此角色为内置角色，不允许删除！");
		}
		if (Global.YES.equals(role.getIsSys()) && !role.getCurrentUser().isSuperAdmin()){
			return renderResult(Global.FALSE, "越权操作，只有超级管理员才能修改此数据！");
		}
		if(roleService.hasUserRole(role)){
			return renderResult(Global.FALSE, "角色"+role.getRoleName()+"关联了用户，删除角色失败！");
		}
		roleService.delete(role);
		return renderResult(Global.TRUE, "删除角色成功！");
	}

//	/**
//	 * 角色分配页面
//	 * 
//	 * @param role
//	 * @param model
//	 * @return
//	 * @deprecated
//	 */
//	@RequiresPermissions("sys:role:edit")
//	@RequestMapping(value = "assign")
//	public String assign(Role role, Model model) {
//		List<User> userList = systemService.findUser(new User(new Role(role
//				.getId())));
//		model.addAttribute("userList", userList);
//		return "modules/sys/roleAssign";
//	}
//
//	/**
//	 * 角色分配 -- 打开角色分配对话框
//	 * 
//	 * @param role
//	 * @param model
//	 * @return
//	 * @deprecated
//	 */
//	@RequiresPermissions("sys:role:view")
//	@RequestMapping(value = "usertorole")
//	public String selectUserToRole(Role role, Model model) {
//		List<User> userList = systemService.findUser(new User(new Role(role
//				.getId())));
//		model.addAttribute("role", role);
//		model.addAttribute("userList", userList);
//		model.addAttribute("selectIds",
//				Collections3.extractToString(userList, "name", ","));
//		model.addAttribute("officeList", officeService.findList(false));
//		return "modules/sys/selectUserToRole";
//	}
//
//	/**
//	 * 角色分配 -- 根据部门编号获取用户列表
//	 * 
//	 * @param officeId
//	 * @param response
//	 * @return
//	 * @deprecated
//	 */
//	@RequiresPermissions("sys:role:view")
//	@ResponseBody
//	@RequestMapping(value = "users")
//	public List<Map<String, Object>> users(String officeId,
//			HttpServletResponse response) {
//		List<Map<String, Object>> mapList = Lists.newArrayList();
//		User user = new User();
//		// user.setOffice(new Office(officeId));
//		Page<User> page = systemService.findUser(new Page<User>(1, -1), user);
//		for (User e : page.getList()) {
//			Map<String, Object> map = Maps.newHashMap();
//			map.put("id", e.getId());
//			map.put("pId", 0);
//			map.put("name", e.getNickname());
//			mapList.add(map);
//		}
//		return mapList;
//	}
//
//	/**
//	 * 角色分配 -- 从角色中移除用户
//	 * 
//	 * @param userId
//	 * @param roleId
//	 * @param redirectAttributes
//	 * @return
//	 * @deprecated
//	 */
//	@RequiresPermissions("sys:role:edit")
//	@RequestMapping(value = "outrole")
//	public String outrole(String userId, String roleId,
//			RedirectAttributes redirectAttributes) {
//		if (Global.isDemoMode()) {
//			addMessage(redirectAttributes, "演示模式，不允许操作！");
//			return "redirect:" + adminPath + "/sys/role/assign?id=" + roleId;
//		}
//		Role role = roleService.getRole(roleId);
////		User user = systemService.getUser(userId);
////		if (UserUtils.getUser().getId().equals(userId)) {
////			addMessage(redirectAttributes, "无法从角色【" + role.getName()
////					+ "】中移除用户【" + user.getName() + "】自己！");
////		} else {
////			if (user.getRoleList().size() <= 1) {
////				addMessage(redirectAttributes, "用户【" + user.getName() + "】从角色【"
////						+ role.getName() + "】中移除失败！这已经是该用户的唯一角色，不能移除。");
////			} else {
////				Boolean flag = roleService.outUserInRole(role, user);
////				if (!flag) {
////					addMessage(redirectAttributes, "用户【" + user.getName()
////							+ "】从角色【" + role.getName() + "】中移除失败！");
////				} else {
////					addMessage(redirectAttributes, "用户【" + user.getName()
////							+ "】从角色【" + role.getName() + "】中移除成功！");
////				}
////			}
////		}
//		return "redirect:" + adminPath + "/sys/role/assign?id=" + role.getId();
//	}
//
//	/**
//	 * 角色分配
//	 * 
//	 * @param role
//	 * @param idsArr
//	 * @param redirectAttributes
//	 * @return
//	 * @deprecated
//	 */
//	@RequiresPermissions("sys:role:edit")
//	@RequestMapping(value = "assignrole")
//	public String assignRole(Role role, String[] idsArr,
//			RedirectAttributes redirectAttributes) {
//		if (Global.isDemoMode()) {
//			addMessage(redirectAttributes, "演示模式，不允许操作！");
//			return "redirect:" + adminPath + "/sys/role/assign?id="
//					+ role.getId();
//		}
//		StringBuilder msg = new StringBuilder();
//		int newNum = 0;
//		for (int i = 0; i < idsArr.length; i++) {
//			User user = systemService.assignUserToRole(role,
//					systemService.getUser(idsArr[i]));
//			if (null != user) {
//				// msg.append("<br/>新增用户【" + user.getName() + "】到角色【" +
//				// role.getName() + "】！");
//				newNum++;
//			}
//		}
//		addMessage(redirectAttributes, "已成功分配 " + newNum + " 个用户" + msg);
//		return "redirect:" + adminPath + "/sys/role/assign?id=" + role.getId();
//	}

	/**
	 * 验证角色名是否有效
	 * @param oldName
	 * @param name
	 * @return
	 */
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "checkName")
	public String checkName(String oldName, String roleName) {
		if (roleName != null && roleName.equals(oldName)) {
			return "true";
		} else if (roleName != null && roleService.getByName(roleName) == null) {
			return "true";
		}
		return "false";
	}

	/**
	 * 验证角色英文名是否有效
	 * @param oldName
	 * @param name
	 * @return
	 */
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "checkEnname")
	public String checkEnname(String oldEnname, String nameEn) {
		if (nameEn != null && nameEn.equals(oldEnname)) {
			return "true";
		} else if (nameEn != null && roleService.getByEnname(nameEn) == null) {
			return "true";
		}
		return "false";
	}

}